'''
Created on Feb 24, 2009

@author: whaleyr
'''

import os
import gradeProcs
from models import Course,Semester,Assignment
from assignment import AssignmentForm

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms

from django import http
from django import shortcuts

class CourseForm(djangoforms.ModelForm):
  class Meta:
    model = Course
    exclude = ['user', 'semester']


def listAll(request, semester_id):
  user = users.GetCurrentUser()
  semester = Semester.get(db.Key.from_path(Semester.kind(), int(semester_id)))
  courses = Course.gql('WHERE user=:1 and semester=:2 ORDER BY title ASC', user, semester)
  form = CourseForm(data=None, instance=None)
    
  return respond(request, user, 'courses', {'semester':semester, 'courses': courses, 'form': form})

def view(request, course_id):
  user = users.GetCurrentUser()
  course = Course.get(db.Key.from_path(Course.kind(), int(course_id)))
  if course is None or course.user != user:
    return http.HttpResponseNotFound('Course does not exist')
  totalScore = 0
  totalPossible = 0
  totalCorpus = 0
  totalCorpusScore = 0
  for assign in course.assignment_set:
    if (assign.score != None):
      totalScore += assign.score
    if (assign.possible != None):
      totalPossible += assign.possible
    if (assign.amountOfCorpus != None):
      totalCorpus += assign.amountOfCorpus
    if (assign.amountOfCorpus != None and assign.score != None and assign.possible != None):
      totalCorpusScore += (assign.score/assign.possible)*assign.amountOfCorpus
  assignment = Assignment(course=course, name='Fill in a name')
  form = AssignmentForm(data=None, instance=assignment)
  if (totalCorpus != 0):
    classScore = (totalCorpusScore*100)/totalCorpus
  else:
    classScore = 0
  return respond(request, user, 'courseDetail', {'course': course, 'form': form, 'totalScore': totalScore, 'totalPossible': totalPossible, 'totalCorpus': totalCorpus, 'classScore': classScore})

def new(request):
  """Create a course."""
  user = users.GetCurrentUser()
  course = None
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to add or edit a course')
  if not request.POST:
    return respond(request, user, 'course', {'form': form, 'course': course})
  form = CourseForm(data=request.POST or None, instance=course)
  errors = form.errors
  if not errors:
    try:
      course = form.save(commit=False)
      course.semester = Semester.get(db.Key.from_path(Semester.kind(), int(request.POST['semesterid'])))
      course.user = users.GetCurrentUser()
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
    return respond(request, user, 'course', {'form': form, 'course': course})
  course.put()
  return http.HttpResponseRedirect('/courses/' + request.POST['semesterid'])

def delete(request, course_id):
  use = users.GetCurrentUser()
  if course_id:
    course = Course.get(db.Key.from_path(Course.kind(), int(course_id)))
    if course is None:
      return http.HttpResponseNotFound('No course exists with that key (%r)' % course_id)
    course.delete()
    gradeProcs.refreshSemData(course.semester)
    return http.HttpResponseRedirect('/courses/' + str(course.semester.key().id()))

def edit(request, course_id):
  """Create or edit a course.  GET shows a blank form, POST processes it."""
  user = users.GetCurrentUser()
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to add or edit a course')

  course = None
  if course_id:
    course = Course.get(db.Key.from_path(Course.kind(), int(course_id)))
    if course is None:
      return http.HttpResponseNotFound('No course exists with that key (%r)' %
                                       course_id)

  form = CourseForm(data=request.POST or None, instance=course)

  if not request.POST:
    return respond(request, user, 'course', {'form': form, 'course': course})

  errors = form.errors
  if not errors:
    try:
      course = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
    return respond(request, user, 'course', {'form': form, 'course': course})

  course.user = users.GetCurrentUser()
  
  course.put()
  gradeProcs.refreshSemData(course.semester)
  return http.HttpResponseRedirect('/courses/'+str(course.semester.key().id()))

def respond(request, user, template, params=None):
  """Helper to render a response, passing standard stuff to the response.

  Args:
    request: The request object.
    user: The User object representing the current user; or None if nobody
      is logged in.
    template: The template name; '.html' is appended automatically.
    params: A dict giving the template parameters; modified in-place.

  Returns:
    Whatever render_to_response(template, params) returns.

  Raises:
    Whatever render_to_response(template, params) raises.
  """
  if params is None:
    params = {}
  if user:
    params['user'] = user
    params['sign_out'] = users.CreateLogoutURL('/')
    params['is_admin'] = (users.IsCurrentUserAdmin() and
                          'Dev' in os.getenv('SERVER_SOFTWARE'))
  else:
    params['sign_in'] = users.CreateLoginURL(request.path)
  if not template.endswith('.html'):
    template += '.html'
  return shortcuts.render_to_response(template, params)

def __init__(selfparams):
  '''
  Constructor
  '''
        